import os
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model
import asyncio
from dotenv import load_dotenv
from icecream import ic


load_dotenv()

class User(Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(50, null=True)
    tg_id = fields.CharField(50, null=True)
    range = fields.CharField(50, null=True)

class Cities(Model):
    id = fields.IntField(pk=True)
    citie = fields.CharField(50)
    coordinates = fields.CharField(50, null=True)
    user = fields.ForeignKeyField('models.User', related_name='cities', on_delete=fields.SET_NULL, null=True)
    active = fields.BooleanField(default=True)
    
    async def deactivate_other_cities(self):
        if self.active and self.id:
            await Cities.filter(user=ic(await self.user)).exclude(id=self.id).delete()
        
    

async def init():
    ic(os.environ.get("TORTOISE"))
    await Tortoise.init(
        db_url=os.getenv("DB_URL"),
        modules={"models": ['models.model']},
    )
    await Tortoise.generate_schemas()
    
    
async def start_db():
    await init()

if __name__ == "__main__":
    run_async(start_db())